import csv
class Emp:
    @staticmethod
    def show_title():
        format_title = '{:<8}{:<8}{:<8}{:<8}'
        print(format_title.format('员工编号','员工姓名','年龄','薪水'))

    def __init__(self,eno,name,age,salary):
        self.eno = eno
        self.name = name
        self.age = age
        self.salary = salary

    def show(self):
        format_data = '{:<11}{:<10}{:<8}{:<8}'
        print(format_data.format(self.eno,self.name,self.age,self.salary))

emps = []
FILE = 'emp.csv'

def show_operator():
    print("请选择一个具体的操作:添加(A)|删除(D)|更新(U)|列表(L)|查询(Q)|退出(E)")

def error_msg(msg):
    print("*********************************************",end='')
    print(f'{msg}',end='')
    print("*********************************************")

def suc_msg(msg):
    print("---------------------------------------------------->",end='')
    print(f"{msg}",end='')
    print("<----------------------------------------------------")

def save():
    dict_emps = [{'eno':e.eno,'name':e.name,'age':e.age,'salary':e.salary} for e in emps]
    with open(FILE,'w',encoding='utf-8',newline='') as f:
        fnames = [x for x in dict_emps[0].keys()]
        writer = csv.DictWriter(f,fieldnames=fnames)
        writer.writeheader()
        writer.writerows(dict_emps)

def load():
    try:
        with open(FILE,'r',encoding='utf-8') as f:
            reader = csv.DictReader(f)
            for data in reader:
                emp = Emp(data['eno'],data['name'],data['age'],data['salary'])
                emps.append(emp)
    except FileNotFoundError:
        f = open(FILE,'w',encoding='utf-8')
        f.close()

def load_emp(no):
    for e in emps:
        if e.eno == no:
            return e
    return None

def add_emp():
    no = input('请输入员工号:')
    temp = load_emp(no)
    if temp!=None:
        error_msg('添加的员工已经存在!不能添加!')
        return
    name = input('请输入员工名称')
    age = input('请输入员工年龄')
    salary = input('请输入员工薪水')
    emp = Emp(no,name,age,salary)
    emps.append(emp)
    suc_msg('添加员工成功!')

def delete_emp():
    no = input('请输入员工号:')
    temp = load_emp(no)
    if temp == None:
        error_msg('删除员工不存在')
        return
    emps.remove(temp)
    suc_msg('删除员工成功!')

def update_emp():
    no = input('请输入员工号:')
    temp = load_emp(no)
    if temp == None:
        error_msg('更新的员工不存在!')
        return
    name = input(f'输入员工姓名[{temp.name}]:')
    age = input(f'输入员工年龄[{temp.age}]:')
    salary = input(f'输入员工薪水[{temp.salary}]:')
    if name:
        temp.name = name
    if age:
        temp.age = age
    if salary:
        temp.salary=salary
    suc_msg(f'更新员工{temp.name}成功')

def query_emp():
    op = input('请选择相应的操作:A(根据name查询)|N(根据员工号查询)')
    if op.upper()=='A':
        q = input('请输入要查询的用户名:')
        temps = []
        for e in emps:
            if e.name.find(q)>=0:
                temps.append(e)
        if len(temps)>0:
            Emp.show_title()
            for e in temps:
                e.show()
        else:
            suc_msg('查询的员工不存在!')
    elif op.upper()=='N':
        q = input('请输入要查询的员工号:')
        for e in emps:
            if e.eno==q:
                Emp.show_title()
                e.show()
                break
        else:
           suc_msg('查询的员工不存在!')
    else:
        error_msg('查询选择不正确!')
def main():
    load()
    while True:
        show_operator()
        op = input("请输入相应的操作:")
        if op.upper()=='A':
            add_emp()
            save()
        elif op.upper()=='D':
            delete_emp()
            save()
        elif op.upper()=='U':
            update_emp()
            save()
        elif op.upper()=='L':
            Emp.show_title()
            for emp in emps:
                emp.show()
        elif op.upper()=='Q':
            query_emp()
        elif op.upper()=='E':
            suc_msg('欢迎再次使用我们的系统!')
            break
        else:
            error_msg('请选择一个正确的操作!')

if __name__ == '__main__':
    # Emp.show_title()
    # emp = Emp('001','张安',23,1999)
    # emp.show()
    main()